#include "gpio_device.h"
#include "uart_device.h"
#include "timer_device.h"
#include "my_errno.h"
#include <stdio.h>

#ifndef NULL
#define NULL (void *)0
#endif

PGPIODevice ptLEDBlue = NULL;
PGPIODevice ptLEDGreen = NULL;
PGPIODevice ptLEDWhite = NULL;
PGPIODevice ptKey1 = NULL;
PGPIODevice ptKey2 = NULL;
PTimerDevice ptTimer2 = NULL;
PTimerDevice ptTimer6 = NULL;

PUARTDevice ptUART1 = NULL;




void bsp_periodOnTimer(void)
{	
	ptKey1->KeyScan(ptKey1);
	ptKey2->KeyScan(ptKey2);
}

int bsp_moduleInit(void)
{
	ptLEDWhite = GetGPIODevice("led_white");
	if (NULL == ptLEDWhite)
		return -EINVAL;
	ptLEDBlue = GetGPIODevice("led_blue");
	if (NULL == ptLEDWhite)
		return -EINVAL;
	ptLEDGreen = GetGPIODevice("led_green");
	if (NULL == ptLEDGreen)
		return -EINVAL;
	
	ptKey1 = GetGPIODevice("key1");
	if (NULL == ptKey1)
		return -EINVAL;
	ptKey2 = GetGPIODevice("key2");
	if (NULL == ptKey2)
		return -EINVAL;

/*	ptTimer2 = GetTimerDevice("timer2");
	if (NULL == ptTimer2)
		return -EINVAL;
	ptTimer2->Init(ptTimer2);
	ptTimer2->Callback = bsp_periodOnTimer;*/

	ptTimer6 = GetTimerDevice("timer6");
	if (NULL == ptTimer6)
		return -EINVAL;
	ptTimer6->Init(ptTimer6);
	ptTimer6->Callback = bsp_periodOnTimer;

	ptUART1 =GetUARTDevice("usart1");
	if (NULL == ptUART1)
		return -EINVAL;
	ptUART1->Init(ptUART1);

	return ESUCCESS;
}


//---------------------获取--------------------
//获取按键1的状态，返回值: 0-未按下 /  			  1-按下
uint8_t bsp_getKey1(void)
{
	uint8_t state;
	state = ptKey1->value;	//value: 0-按下   1-未按下
	state = (state == 1) ? 0 : 1;
	return state;
}

//获取按键2的状态，返回值: 0-未按下 /  			  1-按下
uint8_t bsp_getKey2(void)
{
	uint8_t state;
	state = ptKey2->value;	//value: 0-按下   1-未按下
	state = (state == 1) ? 0 : 1;
	return state;
}



//---------------------设置--------------------
int bsp_setLEDBlueCtrl(uint8_t ctrl)
{
	int res = -EIO;	
	if (NULL == ptLEDBlue)
		return res;
		
	res = ptLEDBlue->Write(ptLEDBlue, ctrl);
	
	return res;
}

int bsp_setLEDGreenCtrl(uint8_t ctrl)
{
	int res = -EIO;                                                      
	if (NULL == ptLEDGreen)
		return res;

	res = ptLEDGreen->Write(ptLEDGreen, ctrl);
	
	return res;
}

int bsp_setLEDWhiteCtrl(uint8_t ctrl)
{
	int res = -EIO;
	if (NULL == ptLEDWhite)
		return res;
		
	res = ptLEDWhite->Write(ptLEDWhite, ctrl);
	
	return res;
}

//---------------------通信--------------------

int bsp_debugComWrite(uint8_t *pData, uint16_t len, uint16_t timeoutMS)
{
	int res = ESUCCESS;
	if (NULL == ptUART1)
		return res;

	res =ptUART1->Send(ptUART1, (unsigned char *)pData, (int)len, (int)timeoutMS);
	return res;
}

#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

//STM32cubeIDE下
PUTCHAR_PROTOTYPE
{
    //HAL_UART_Transmit(&huart3 , (uint8_t *)&ch, 1,0x200);
	bsp_debugComWrite((uint8_t *)&ch, 1, 1000);
    return ch;
}


//int fputc(int ch, FILE *f)  
//{
//	bsp_debugComWrite((uint8_t *)&ch, 1, 1000);
//	return ch;
//}


